package com.xiaoxiaoniu.airoleplay.services;

import lombok.Getter;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Pattern;

@Service
public class RoleSkillService {

    private final Random random = new Random();

    // 角色特殊技能触发词和响应（增强版）
    private static final Map<String, List<Skill>> ROLE_SKILLS = new HashMap<>();

    // 技能优先级常量
    private static final int PRIORITY_HIGH = 3;
    private static final int PRIORITY_MEDIUM = 2;
    private static final int PRIORITY_LOW = 1;

    static {
        initializeHarryPotterSkills();
        initializeSocratesSkills();
        initializeSherlockSkills();
        initializeEinsteinSkills();
    }

    private static void initializeHarryPotterSkills() {
        List<Skill> harrySkills = new ArrayList<>();

        // 高优先级技能 - 精确匹配
        harrySkills.add(new Skill(
                "魔法咒语",
                Arrays.asList("expelliarmus", "expecto patronum", "wingardium leviosa", "lumos", "accio"),
                Arrays.asList(
                        "Expelliarmus！这是缴械咒，我最常用的咒语之一！",
                        "Expecto Patronum！呼神护卫，用来驱逐摄魂怪的强大咒语！",
                        "Wingardium Leviosa！羽加迪姆勒维奥萨，让物体漂浮起来的咒语！",
                        "Lumos！荧光闪烁，在黑暗中照亮前路！"
                ).toArray(new String[0]),
                PRIORITY_HIGH,
                true  // 精确匹配
        ));

        // 中优先级技能 - 关键词匹配
        harrySkills.add(new Skill(
                "魁地奇知识",
                Arrays.asList("魁地奇", "金色飞贼", "光轮", "扫帚", "找球手"),
                Arrays.asList(
                        "我是格兰芬多的找球手！金色飞贼可难抓了，但抓住它的感觉真刺激！",
                        "光轮2000是我最喜欢的扫帚，骑在上面飞翔的感觉太棒了！",
                        "魁地奇比赛最重要的是团队配合，就像我们对抗斯莱特林时那样！"
                ).toArray(new String[0]),
                PRIORITY_MEDIUM,
                false
        ));

        harrySkills.add(new Skill(
                "霍格沃茨生活",
                Arrays.asList("霍格沃茨", "格兰芬多", "斯莱特林", "赫奇帕奇", "拉文克劳", "大礼堂", "魔法学校"),
                Arrays.asList(
                        "霍格沃茨有四个学院：勇敢的格兰芬多、精明的斯莱特林、忠诚的赫奇帕奇和智慧的拉文克劳！",
                        "大礼堂的天花板被施了魔法，看起来跟外面的天空一模一样！",
                        "在霍格沃茨，我最喜欢的是魔法史课，虽然宾斯教授讲课有点无聊..."
                ).toArray(new String[0]),
                PRIORITY_MEDIUM,
                false
        ));

        // 低优先级技能 - 一般话题
        harrySkills.add(new Skill(
                "魔法世界",
                Arrays.asList("魔法", "咒语", "魔杖", "巫师", "麻瓜"),
                Arrays.asList(
                        "魔法世界充满了奇妙的事物，但也要小心黑魔法的危险！",
                        "每个巫师的魔杖都是独特的，我的魔杖是冬青木，凤凰羽毛芯！",
                        "麻瓜世界也有很多有趣的东西，比如电视和手机！"
                ).toArray(new String[0]),
                PRIORITY_LOW,
                false
        ));

        ROLE_SKILLS.put("哈利波特", harrySkills);
    }

    private static void initializeSocratesSkills() {
        List<Skill> socratesSkills = new ArrayList<>();

        socratesSkills.add(new Skill(
                "哲学提问",
                Arrays.asList("什么是", "为什么", "如何", "何为", "意义"),
                Arrays.asList(
                        "让我用苏格拉底式提问来引导你思考：你认为{keyword}的真正含义是什么？",
                        "关于{keyword}，请问你如何定义这个概念？让我们通过对话来探索。",
                        "知识始于承认无知。关于{keyword}，你有什么更深的理解？"
                ).toArray(new String[0]),
                PRIORITY_HIGH,
                false
        ));

        socratesSkills.add(new Skill(
                "真理探索",
                Arrays.asList("真理", "真实", "真相", "事实"),
                Arrays.asList(
                        "真理需要通过对立面来发现。关于{keyword}，让我们从不同角度来审视。",
                        "未经审视的{keyword}不值得相信。你认为什么是真正的{keyword}？",
                        "通过辩证法的讨论，我们可以更接近{keyword}的本质。"
                ).toArray(new String[0]),
                PRIORITY_MEDIUM,
                false
        ));

        socratesSkills.add(new Skill(
                "美德讨论",
                Arrays.asList("美德", "道德", "善", "正义", "公正"),
                Arrays.asList(
                        "美德即知识。你提到的{keyword}，与个人的品德修养有何关联？",
                        "无人故意为恶，作恶是由于无知。你认为{keyword}如何影响人的行为？",
                        "让我们探讨什么是真正的{keyword}，以及它如何让社会变得更美好。"
                ).toArray(new String[0]),
                PRIORITY_MEDIUM,
                false
        ));

        socratesSkills.add(new Skill(
                "人生思考",
                Arrays.asList("人生", "生命", "存在", "价值", "目的"),
                Arrays.asList(
                        "未经审视的人生不值得度过。你如何看待{keyword}的意义？",
                        "关于{keyword}，我认为最重要的是不断追问和反思。",
                        "{keyword}的奥秘需要我们通过理性思考来解开。"
                ).toArray(new String[0]),
                PRIORITY_LOW,
                false
        ));

        ROLE_SKILLS.put("苏格拉底", socratesSkills);
    }

    private static void initializeSherlockSkills() {
        List<Skill> sherlockSkills = new ArrayList<>();

        sherlockSkills.add(new Skill(
                "推理分析",
                Arrays.asList("推理", "推断", "分析", "结论", "逻辑"),
                Arrays.asList(
                        "当你排除了所有不可能，剩下的不管多么难以置信，一定就是真相。关于{keyword}，我观察到...",
                        "基于现有的线索，我对{keyword}有以下推理：首先...其次...",
                        "逻辑是推理的基础。让我们用演绎法来分析{keyword}。"
                ).toArray(new String[0]),
                PRIORITY_HIGH,
                false
        ));

        sherlockSkills.add(new Skill(
                "案件调查",
                Arrays.asList("案件", "凶手", "证据", "嫌疑人", "侦探"),
                Arrays.asList(
                        "这真是个有趣的{keyword}！让我们从基本要素开始分析。",
                        "每个{keyword}都有其独特的逻辑，关键在于找到那个不协调的音符。",
                        "关于这个{keyword}，我已经注意到几个关键细节..."
                ).toArray(new String[0]),
                PRIORITY_HIGH,
                false
        ));

        sherlockSkills.add(new Skill(
                "观察技巧",
                Arrays.asList("观察", "细节", "痕迹", "线索", "发现"),
                Arrays.asList(
                        "观察，我亲爱的朋友，观察！你注意到了什么不寻常的地方吗？",
                        "从{keyword}中，我可以推断出很多信息。比如...",
                        "{keyword}的重要性不容忽视，它往往是破案的关键。"
                ).toArray(new String[0]),
                PRIORITY_MEDIUM,
                false
        ));

        sherlockSkills.add(new Skill(
                "科学方法",
                Arrays.asList("科学", "实验", "数据", "假设", "验证"),
                Arrays.asList(
                        "科学方法是破案的利器。对于{keyword}，我们需要先建立假设，然后验证。",
                        "数据不会说谎。让我们用科学的态度来对待{keyword}。",
                        "{keyword}需要严谨的验证过程，不能仅凭直觉判断。"
                ).toArray(new String[0]),
                PRIORITY_LOW,
                false
        ));

        ROLE_SKILLS.put("福尔摩斯", sherlockSkills);
    }

    private static void initializeEinsteinSkills() {
        List<Skill> einsteinSkills = new ArrayList<>();

        einsteinSkills.add(new Skill(
                "物理理论",
                Arrays.asList("相对论", "量子", "光子", "时空", "引力"),
                Arrays.asList(
                        "关于{keyword}，让我用一个简单的比喻来解释：想象你在一辆运动的火车上...",
                        "{keyword}改变了我们对宇宙的理解。最奇妙的是...",
                        "我用思想实验来理解{keyword}，比如想象追逐一束光会看到什么。"
                ).toArray(new String[0]),
                PRIORITY_HIGH,
                false
        ));

        einsteinSkills.add(new Skill(
                "科学思维",
                Arrays.asList("科学", "研究", "理论", "发现", "创新"),
                Arrays.asList(
                        "想象力比知识更重要。关于{keyword}，我们需要跳出传统思维。",
                        "{keyword}的发展需要大胆的假设和严谨的验证。",
                        "我始终对{keyword}保持着孩子般的好奇心。"
                ).toArray(new String[0]),
                PRIORITY_MEDIUM,
                false
        ));

        einsteinSkills.add(new Skill(
                "人生哲学",
                Arrays.asList("人生", "价值", "和平", "教育", "好奇心"),
                Arrays.asList(
                        "不要努力成为成功的人，要努力成为有价值的人。{keyword}对此很重要。",
                        "关于{keyword}，我认为最重要的是保持独立思考和好奇心。",
                        "{keyword}的意义在于它如何让世界变得更美好。"
                ).toArray(new String[0]),
                PRIORITY_MEDIUM,
                false
        ));

        einsteinSkills.add(new Skill(
                "幽默智慧",
                Arrays.asList("幽默", "笑话", "有趣", "聪明", "智慧"),
                Arrays.asList(
                        "关于{keyword}，我有一个小笑话：为什么...",
                        "{keyword}和科学研究一样，都需要一点幽默感！",
                        "我经常用{keyword}来让复杂的理论变得更容易理解。"
                ).toArray(new String[0]),
                PRIORITY_LOW,
                false
        ));

        ROLE_SKILLS.put("爱因斯坦", einsteinSkills);
    }

    /**
     * 检查并应用角色技能 - 增强版
     * 支持多级优先级和智能匹配
     */
    public String checkAndApplySkill(String role, String userMessage) {
        List<Skill> roleSkills = ROLE_SKILLS.get(role);
        if (roleSkills == null || roleSkills.isEmpty()) {
            return null;
        }

        // 按优先级分组收集触发的技能
        Map<Integer, List<Skill>> triggeredSkillsByPriority = new HashMap<>();

        for (Skill skill : roleSkills) {
            String matchedTrigger = findMatchingTrigger(skill, userMessage);
            if (matchedTrigger != null) {
                triggeredSkillsByPriority
                        .computeIfAbsent(skill.getPriority(), k -> new ArrayList<>())
                        .add(skill);
            }
        }

        // 按优先级从高到低选择技能
        for (int priority = PRIORITY_HIGH; priority >= PRIORITY_LOW; priority--) {
            List<Skill> highPrioritySkills = triggeredSkillsByPriority.get(priority);
            if (highPrioritySkills != null && !highPrioritySkills.isEmpty()) {
                Skill selectedSkill = highPrioritySkills.get(random.nextInt(highPrioritySkills.size()));
                String matchedTrigger = findMatchingTrigger(selectedSkill, userMessage);
                return formatSkillResponse(selectedSkill, matchedTrigger, userMessage);
            }
        }

        return null;
    }

    /**
     * 查找匹配的触发词
     */
    private String findMatchingTrigger(Skill skill, String userMessage) {
        String lowerMessage = userMessage.toLowerCase();

        for (String trigger : skill.getTriggers()) {
            if (skill.isExactMatch()) {
                // 精确匹配 - 使用正则表达式确保单词边界
                Pattern pattern = Pattern.compile("\\b" + Pattern.quote(trigger.toLowerCase()) + "\\b");
                if (pattern.matcher(lowerMessage).find()) {
                    return trigger;
                }
            } else {
                // 模糊匹配 - 包含即可
                if (lowerMessage.contains(trigger.toLowerCase())) {
                    return trigger;
                }
            }
        }
        return null;
    }

    /**
     * 格式化技能响应
     */
    private String formatSkillResponse(Skill skill, String matchedTrigger, String userMessage) {
        String[] responses = skill.getResponses();
        String response = responses[random.nextInt(responses.length)];

        // 替换模板变量
        if (matchedTrigger != null) {
            response = response.replace("{keyword}", matchedTrigger);
        }
        response = response.replace("{message}", userMessage);

        // 添加技能标识
        return "✨【" + skill.getName() + "】" + response;
    }

    /**
     * 获取智能备用回复（当AI服务不可用时）
     */
    public String getIntelligentFallback(String role, String userMessage) {
        // 先尝试触发技能
        String skillResponse = checkAndApplySkill(role, userMessage);
        if (skillResponse != null) {
            return skillResponse.replace("✨【", "🚫【备用模式】");
        }

        // 如果没有触发技能，使用角色特定的智能回复
        Map<String, String[]> ROLE_RESPONSES = new HashMap<>();
        ROLE_RESPONSES.put("哈利波特", new String[]{
                "梅林的胡子啊！你提到『{message}』，这让我想起了在霍格沃茨的时光。",
                "梅林在上！『{message}』...让我想想，这需要一些魔法来解决！",
                "梅林的魔法！你提到了『{message}』，作为格兰芬多的学生，我认为...",
                "梅林最肥的三角裤！『{message}』真是个有趣的话题！"
        });

        ROLE_RESPONSES.put("苏格拉底", new String[]{
                "我唯一知道的就是我一无所知。但关于『{message}』，让我们通过对话来探索真理。",
                "未经审视的人生不值得度过。你提到『{message}』，请问你如何定义这个概念？",
                "知识始于承认无知。关于『{message}』，你有什么更深的理解？",
                "美德即知识。你提到的『{message}』，与美德有何关联？"
        });

        ROLE_RESPONSES.put("福尔摩斯", new String[]{
                "当你排除了所有不可能，剩下的不管多么难以置信，一定就是真相。关于『{message}』，我观察到...",
                "细节是最重要的。你提到『{message}』，让我注意到几个关键细节...",
                "推理的艺术。从『{message}』中，我可以推断出几个可能性...",
                "基本演绎法。关于『{message}』，让我们从基础事实开始分析..."
        });

        ROLE_RESPONSES.put("爱因斯坦", new String[]{
                "想象力比知识更重要。你提到的『{message}』，让我想到一个有趣的比喻...",
                "疯狂就是重复做同一件事却期待不同结果。关于『{message}』，我们需要创新思考...",
                "宇宙最不可理解之处是它是可理解的。你提到『{message}』，这让我想到物理学的原理...",
                "不要担心你在数学上的困难，我保证我的更大。关于『{message}』，让我们用简单的方式理解..."
        });

        String[] responses = ROLE_RESPONSES.get(role);
        if (responses == null) {
            return "你好！我是" + role + "。你刚才提到：" + userMessage + "，这个话题很有意思！";
        }

        String template = responses[random.nextInt(responses.length)];
        return "🔄【智能回复】" + template.replace("{message}", userMessage);
    }

    /**
     * 获取角色技能统计信息（用于调试和展示）
     */
    public Map<String, Object> getRoleSkillsInfo(String role) {
        Map<String, Object> info = new HashMap<>();
        List<Skill> skills = ROLE_SKILLS.get(role);

        if (skills != null) {
            info.put("skillCount", skills.size());

            List<Map<String, Object>> skillDetails = new ArrayList<>();
            for (Skill skill : skills) {
                Map<String, Object> detail = new HashMap<>();
                detail.put("name", skill.getName());
                detail.put("triggers", skill.getTriggers());
                detail.put("responseCount", skill.getResponses().length);
                detail.put("priority", skill.getPriority());
                detail.put("exactMatch", skill.isExactMatch());
                skillDetails.add(detail);
            }
            info.put("skills", skillDetails);
        } else {
            info.put("skillCount", 0);
            info.put("skills", Collections.emptyList());
        }

        return info;
    }

    /**
     * 技能内部类
     */
    private static class Skill {
        private final String name;
        private final List<String> triggers;
        private final String[] responses;
        private final int priority;
        private final boolean exactMatch;

        public Skill(String name, List<String> triggers, String[] responses, int priority, boolean exactMatch) {
            this.name = name;
            this.triggers = triggers;
            this.responses = responses;
            this.priority = priority;
            this.exactMatch = exactMatch;
        }

        public String getName() { return name; }
        public List<String> getTriggers() { return triggers; }
        public String[] getResponses() { return responses; }
        public int getPriority() { return priority; }
        public boolean isExactMatch() { return exactMatch; }
    }

    /**
     * 测试方法 - 显示所有角色的技能信息
     */
    public void debugAllSkills() {
        System.out.println("=== 角色技能系统调试信息 ===");
        for (String role : ROLE_SKILLS.keySet()) {
            System.out.println("\n角色: " + role);
            Map<String, Object> info = getRoleSkillsInfo(role);
            System.out.println("技能数量: " + info.get("skillCount"));

            @SuppressWarnings("unchecked")
            List<Map<String, Object>> skills = (List<Map<String, Object>>) info.get("skills");
            for (Map<String, Object> skill : skills) {
                System.out.println("  - " + skill.get("name") + " (优先级: " + skill.get("priority") + ")");
                System.out.println("    触发词: " + skill.get("triggers"));
            }
        }
        System.out.println("===========================");
    }
}